package net.oschina.db;

/**
 * Created by rex on 2015/3/10.
 */

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.beans.PropertyVetoException;
import java.util.Properties;

public class DBPool {
    private static DBPool dbPool;
    private ComboPooledDataSource dataSource;

    private DBPool() {
        String configPath = System. getProperty ("user.dir")+System.getProperty("file.separator")+"db.properties";
        // Read configuration
        Properties prop = new Properties();
        InputStream in = null;

        File f = new File(configPath);
        try {
            in = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            System.out.println("[E] open mail config file failed");
            return;
        }

        String host = "";
        String user = "";
        String password = "";
        String dbname = "";
        int port = 3306;

        try {
            prop.load(in);
            host = prop.getProperty("host").trim();
            user = prop.getProperty("user").trim();
            password = prop.getProperty("password").trim();
            port = Integer.parseInt(prop.getProperty("port").trim());
            dbname = prop.getProperty("dbname").trim();
        } catch (IOException e) {
            System.out.println("[E] Read Email configuration failed");
        }

        try {
            dataSource = new ComboPooledDataSource();
            dataSource.setUser(user);
            dataSource.setPassword(password);
            dataSource.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + dbname + "?autoReconnect=true&useUnicode=true&characterEncoding=utf8");
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setInitialPoolSize(2);
            dataSource.setMinPoolSize(1);
            dataSource.setMaxPoolSize(10);
            dataSource.setMaxStatements(50);
            dataSource.setMaxIdleTime(60);
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }

    public final static DBPool getInstance() {
        if(dbPool!=null){
            return dbPool;
        }else{
            dbPool = new DBPool();
            return dbPool;
        }
    }

    public final Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("Cannot get connection from datasource", e);
        }
    }

}